package com.cw.jeeyt.controller.security;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.service.bo.security.SecurityUserRoleBo;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.intf.security.SecurityUserService;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 用户信息控制层
 *
 * @author chenw
 * @version 1.0.0
 *
 */
@Controller
@RequestMapping("/securityUser")
public class SecurityUserController extends BaseController {
    @Resource
    private SecurityUserService securityUserService;

    /**
     * 跳转到用户信息列表查询页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query() throws Exception {
        ModelAndView mv = new ModelAndView("security/securityUser_index");
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 跳转到修改密码页面
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-updatePassword")
    public ModelAndView toUpdatePassword(Long id) {
        ModelAndView mv = new ModelAndView("security/securityUser_updatePassword");
        mv.addObject("id", id);
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listUser")
    public ResultData listUser(@RequestBody DataTable dataTable) throws Exception {

        SecurityUserBo userBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            SecurityUserBo.class);
        if (userBo == null) {
            userBo = new SecurityUserBo();
        }
        PageInfo<SecurityUserBo> pageInfo = securityUserService.queryByPage(userBo, dataTable.getStart(),
            dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到用户信息表单页面
     *
     * @param id 主键
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView editForm(Long id, String operation) throws Exception {

        ModelAndView mv = new ModelAndView("security/securityUser_form");
        SecurityUserBo userBo = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            userBo = new SecurityUserBo();
        } else if (EnumOperateFlag.EDIT.getCode()
            .equals(operation) || EnumOperateFlag.VIEW.getCode()
            .equals(operation)) {
            userBo = securityUserService.getUserById(id);
            StringBuffer roleNames = new StringBuffer("");
            StringBuffer roleIds = new StringBuffer("");
            Set<SecurityUserRoleBo> surList = userBo.getUserRoles();
            if (surList != null && !surList.isEmpty()) {
                int i = 0;
                Iterator<SecurityUserRoleBo> it = surList.iterator();
                while (it.hasNext()) {
                    SecurityUserRoleBo securityUserRoleBo = it.next();
                    if (i == 0) {
                        roleNames.append(securityUserRoleBo.getRoleName());
                        roleIds.append(securityUserRoleBo.getRoleId());
                    } else {
                        roleNames.append("," + securityUserRoleBo.getRoleName());
                        roleIds.append("," + securityUserRoleBo.getRoleId());
                    }
                    i++;
                }
            }
            mv.addObject("roleNames", roleNames.toString());
            mv.addObject("roleIds", roleIds.toString());
        } else {
            userBo = securityUserService.getUserById(id);
            mv = new ModelAndView("security/securityUser_home");
            operation = EnumOperateFlag.EDIT.getCode();
        }
        mv.addObject("securityUser", userBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 根据操作类型保存用户信息数据
     *
     * @param userBo
     * @param operation add 新增  edit 修改
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    public JsonResultDto saveUser(SecurityUserBo userBo, String operation) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                securityUserService.insert(userBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                securityUserService.update(userBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("保存失败:" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 根据操作类型保存用户信息数据
     *
     * @param userBo
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/modifyUser", method = RequestMethod.POST)
    public JsonResultDto modifyUser(SecurityUserBo userBo) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityUserService.modifyUser(userBo);
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("保存失败:" + e.getMessage());

        }
        return jsonResultDto;
    }

    /**
     * 根据操作类型保存用户信息数据
     *
     * @param userBo
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public JsonResultDto updatePassword(SecurityUserBo userBo) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            String password = userBo.getPassword();
            String newPassword = userBo.getNewPassword();
            String reNewPassword = userBo.getReNewPassword();
            if (StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(
                reNewPassword)) {
                jsonResultDto.setMsg("密码信息不能为空");
                return jsonResultDto;
            }
            if (!newPassword.equals(reNewPassword)) {
                jsonResultDto.setMsg("新密码与确认密码不一致，请重新输入！");
                return jsonResultDto;
            }
            if (password.equals(newPassword)) {
                jsonResultDto.setMsg("旧密码与新密码一致，请重新输入！");
                return jsonResultDto;
            }
            securityUserService.updatePassword(userBo);
            jsonResultDto.setMsg("密码修改成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("密码修改失败:" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 删除用户信息
     *
     * @param userBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto delete(SecurityUserBo userBo) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityUserService.delete(userBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 删除用户信息
     *
     * @param id
     * @throws Exception
     */
    @RequestMapping(value = "/resetPwd")
    @ResponseBody
    public JsonResultDto resetPwd(Long id) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            String resetPwd = securityUserService.resetPwd(id);
            jsonResultDto.setSuccess(true);
            jsonResultDto.setMsg("密码重置成功,新的密码：" + resetPwd);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("密码重置失败：" + e.getMessage());
        }
        return jsonResultDto;
    }
}
